{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 条件判断和循环\n",
    "\n",
    "#### if语句\n",
    "\n",
    "#### 语法规则\n",
    "\n",
    "1. 语句是逐个运行\n",
    "2. 块和语句的边界自动检测\n",
    "3. 复合语句 = 首行 + “：” + 缩进语句\n",
    "4. 空白行， 空格以及注释通常都会忽略\n",
    "\n",
    "例子：\n",
    "\n",
    "```python\n",
    "if 今天发工资:\n",
    "\n",
    "    先还信用卡的钱\n",
    "\n",
    "    if 有剩余:\n",
    "\n",
    "        又可以happy了，O(∩_∩)O哈哈~\n",
    "\n",
    "    else:\n",
    "\n",
    "        噢，no。。。还的等30天\n",
    "else:\n",
    "\n",
    "    盼着发工资\n",
    "```\n",
    "\n",
    "### 判断的定义\n",
    "\n",
    "* 如果 **条件满足**，才能做某件事情，\n",
    "* 如果 **条件不满足**，就做另外一件事情，或者什么也不做\n",
    "\n",
    ">\n",
    "> **判断语句** 又被称为 “分支语句”，正是因为有了判断，才让程序有了很多的分支\n",
    "\n",
    "\n",
    " if 判断语句基本语法\n",
    "\n",
    "在 `Python` 中，**if 语句** 就是用来进行判断的，格式如下：\n",
    "\n",
    "```python\n",
    "if 要判断的条件:\n",
    "    条件成立时，要做的事情\n",
    "    ……\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "今年多大了？1\n",
      "你的年龄 1\n",
      "这句代码什么时候执行?\n"
     ]
    }
   ],
   "source": [
    "#定义年龄变量\n",
    "age = int(input(\"今年多大了？\"))\n",
    "print('你的年龄', age)\n",
    "\n",
    "# 逻辑分支\n",
    "if age >= 18:\n",
    "    print ('成年人')\n",
    "\n",
    "#思考！- 无论条件是否满足都会执行\n",
    "print(\"这句代码什么时候执行?\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "注意: Python代码的缩进规则。具有相同缩进的代码被视为代码块，上面的3，4行`print`语句就构成一个代码块（但不包括第5行的print）。如果`if`语句判断为`True`，就会执行这个代码块。\n",
    "\n",
    "缩进请严格按照Python的习惯写法：4个空格，不要使用`Tab`，更不要混合`Tab`和`空格`，否则很容易造成因为缩进引起的语法错误。\n",
    "\n",
    "注意: `if`语句后接表达式，然后用`:`表示代码块开始。\n",
    "\n",
    "\n",
    "### else 处理条件不满足的情况\n",
    "\n",
    "**思考**\n",
    "\n",
    "在使用 `if` 判断时，只能做到满足条件时要做的事情。那如果需要在 **不满足条件的时候**，做某些事情，该如何做呢？\n",
    "\n",
    "**答案**\n",
    "\n",
    "`else`，格式如下：\n",
    "\n",
    "```python\n",
    "if 要判断的条件:\n",
    "    条件成立时，要做的事情\n",
    "    ……\n",
    "else:\n",
    "    条件不成立时，要做的事情\n",
    "    ……\n",
    "```\n",
    "\n",
    "**注意**：\n",
    "\n",
    "* `if` 和 `else` 语句以及各自的缩进部分共同是一个 **完整的代码块**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "今年多大了？1\n",
      "你还没长大，应该回家写作业！\n",
      "这句代码什么时候执行?\n"
     ]
    }
   ],
   "source": [
    "# 1. 输入用户年龄\n",
    "age = int(input(\"今年多大了？\"))\n",
    "\n",
    "# 2. 判断是否满 18 岁\n",
    "# if 语句以及缩进部分的代码是一个完整的语法块\n",
    "if age >= 18:\n",
    "    print(\"可以进网吧嗨皮……\")\n",
    "else:\n",
    "    print(\"你还没长大，应该回家写作业！\")\n",
    "    \n",
    "print(\"这句代码总是执行\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 逻辑运算\n",
    "\n",
    "* 在程序开发中，通常 **在判断条件时**，会需要同时判断多个条件\n",
    "* 只有多个条件都满足，才能够执行后续代码，这个时候需要使用到 **逻辑运算符**\n",
    "* **逻辑运算符** 可以把 **多个条件** 按照 **逻辑** 进行 **连接**，变成 **更复杂的条件**\n",
    "* Python 中的 **逻辑运算符** 包括：**与 and**／**或 or**／**非 not** 三种\n",
    "\n",
    "### 3.1 `and`\n",
    "\n",
    "```\n",
    "条件1 and 条件2\n",
    "```\n",
    "\n",
    "* **与**／**并且**\n",
    "* 两个条件同时满足，返回 `True`\n",
    "* 只要有一个不满足，就返回 `False`\n",
    "\n",
    "| 条件 1 | 条件 2 | 结果 |\n",
    "| :---: | :---: | :---: |\n",
    "| 成立 | 成立 | 成立 |\n",
    "| 成立 | 不成立 | 不成立 |\n",
    "| 不成立 | 成立 | 不成立 |\n",
    "| 不成立 | 不成立 | 不成立 |\n",
    "\n",
    "### 3.2 `or`\n",
    "\n",
    "```\n",
    "条件1 or 条件2\n",
    "```\n",
    "\n",
    "* **或**／**或者**\n",
    "* 两个条件只要有一个满足，返回 `True`\n",
    "* 两个条件都不满足，返回 `False`\n",
    "\n",
    "| 条件 1 | 条件 2 | 结果 |\n",
    "| :---: | :---: | :---: |\n",
    "| 成立 | 成立 | 成立 |\n",
    "| 成立 | 不成立 | 成立 |\n",
    "| 不成立 | 成立 | 成立 |\n",
    "| 不成立 | 不成立 | 不成立 |\n",
    "\n",
    "### 3.3 `not`\n",
    "\n",
    "```\n",
    "not 条件\n",
    "```\n",
    "\n",
    "* **非**／**不是**\n",
    "\n",
    "| 条件 | 结果 |\n",
    "| :---: | :---: |\n",
    "| 成立 | 不成立 |\n",
    "| 不成立 | 成立 |\n",
    "\n",
    "\n",
    "#### 逻辑运算演练\n",
    "\n",
    "练习: 定义两个整数变量 `python_score`、`c_score`，编写代码判断成绩\n",
    "\n",
    "    * 要求只要有一门成绩 > 60 分就算合格"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 练习1: 定义两个整数变量 python_score、c_score，编写代码判断成绩\n",
    "\n",
    "要求只要有一门成绩 > 60 分就算合格"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "invalid syntax (<ipython-input-1-feefbdf12ad3>, line 5)",
     "output_type": "error",
     "traceback": [
      "\u001b[1;36m  File \u001b[1;32m\"<ipython-input-1-feefbdf12ad3>\"\u001b[1;36m, line \u001b[1;32m5\u001b[0m\n\u001b[1;33m    if python_score > 60 ??? c_score > 60:   # 填入 and，or， not ?\u001b[0m\n\u001b[1;37m                         ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid syntax\n"
     ]
    }
   ],
   "source": [
    "python_score = 50\n",
    "c_score = 50\n",
    "# 只要有一门成绩 > 60 分就算合格\n",
    "if python_score > 60 ??? c_score > 60:   # 填入 and，or， not ?\n",
    "    print(\"考试通过\")\n",
    "else:\n",
    "    print(\"再接再厉！\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##  if 语句进阶\n",
    "\n",
    "###  `elif`\n",
    "\n",
    "* 在开发中，使用 `if` 可以 **判断条件**\n",
    "* 使用 `else` 可以处理 **条件不成立** 的情况\n",
    "* 但是，如果希望 **再增加一些条件**，**条件不同，需要执行的代码也不同** 时，就可以使用 `elif` \n",
    "* 语法格式如下：\n",
    "\n",
    "```python\n",
    "if 条件1:\n",
    "    条件1满足执行的代码\n",
    "    ……\n",
    "elif 条件2:\n",
    "    条件2满足时，执行的代码\n",
    "    ……\n",
    "elif 条件3:\n",
    "    条件3满足时，执行的代码\n",
    "    ……\n",
    "else:\n",
    "    以上条件都不满足时，执行的代码\n",
    "    ……\n",
    "```\n",
    "\n",
    "* 对比逻辑运算符的代码\n",
    "\n",
    "```python\n",
    "if 条件1 and 条件2:\n",
    "    条件1满足 并且 条件2满足 执行的代码\n",
    "    ……\n",
    "```\n",
    "\n",
    "**注意**\n",
    "\n",
    "1. `elif` 和 `else` 都必须和 `if` 联合使用，而不能单独使用\n",
    "2. 可以将 `if`、`elif` 和 `else` 以及各自缩进的代码，看成一个 **完整的代码块**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#我们可以用 if ... 多个elif ... else ... 的结构\n",
    "if age >= 18:\n",
    "    print('成年人')\n",
    "elif age >= 13:\n",
    "    print('青年人')\n",
    "elif age >= 3:\n",
    "    print ('儿童')\n",
    "else:\n",
    "    print ('婴儿')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 练习2：\n",
    "\n",
    "如果按照分数划定结果：\n",
    "\n",
    "    90分或以上：excellent\n",
    "\n",
    "    80分或以上：good\n",
    "\n",
    "    60分或以上：passed\n",
    "\n",
    "    60分以下：failed\n",
    "\n",
    "请编写程序根据分数打印结果。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "score = 85\n",
    "if score >= 90:\n",
    "    print ???\n",
    "elif score ??? 80:\n",
    "    print ???\n",
    "elif score >= 60:\n",
    "    print ???\n",
    "else:\n",
    "    print ???"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 循环\n",
    "\n",
    "\n",
    "##  程序的三大流程\n",
    "\n",
    "* 在程序开发中，一共有三种流程方式：\n",
    "    * **顺序** —— **从上向下**，顺序执行代码\n",
    "    * **分支** —— 根据条件判断，决定执行代码的 **分支**\n",
    "    * **循环** —— 让 **特定代码 重复** 执行\n",
    "\n",
    "### Python 之 for循环\n",
    "\n",
    "#### range 使用"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 默认是从0开始，到小于5的整数\n",
    "for number in range(5):\n",
    "    print(number)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 注意开始的数字，2是包括在内\n",
    "for number in range(2, 5):\n",
    "    print(number)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for number in range(0, 10, 2):  # 最后一个数字是步长，隔开2个\n",
    "    print(number)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 列表循环读取"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# list或tuple可以表示一个有序集合。如果我们想依次访问一个list中的每一个元素呢？比如 list：\n",
    "\n",
    "L = ['Adam', 'Lisa', 'Bart']\n",
    "print(L[0])\n",
    "print(L[1])\n",
    "print(L[2])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如果list只包含几个元素，这样写还行，如果list包含1万个元素，我们就不可能写1万行print。\n",
    "\n",
    "这时，循环就派上用场了。\n",
    "\n",
    "Python的 for 循环就可以依次把list或tuple的每个元素迭代出来："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "L = ['Adam', 'Lisa', 'Bart']\n",
    "for name in L:\n",
    "    print(name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### enumerate()\n",
    "\n",
    "如果你需要索引，可以加上这个，那么会一起输出索引\n",
    "\n",
    "enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列，同时列出数据和数据下标，一般用在 for 循环当中。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "L = ['Adam', 'Lisa', 'Bart']\n",
    "for idx, val in enumerate(L):\n",
    "    print('索引(序号）: {}, 值（名字）: {}'.format(idx, val))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 练习： 求 L=[12,28,24,25,99]的总和\n",
    "L=[12,28,24,25,99]\n",
    "total = 0 # 记录总和\n",
    "for num in L:\n",
    "    ???\n",
    "print(total)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sum(L)  # 求和的另一种方式"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Python之 while循环\n",
    "和 for 循环不同的另一种循环是 while 循环，while 循环不会迭代 list 或 tuple 的元素，而是根据表达式判断循环是否结束。\n",
    "\n",
    "比如要从 0 开始打印不大于 N 的整数：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "N = 10\n",
    "x = 0\n",
    "while x <= N:\n",
    "    print(x)\n",
    "    x = x + 1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "while循环每次先判断 x < = N，如果为True，则执行循环体的代码块，否则，退出循环。\n",
    "\n",
    "在循环体内，x = x + 1 会让 x 不断增加，最终因为 x < = N 不成立而退出循环。\n",
    "\n",
    "如果没有这一个语句，while循环在判断 x < = N 时总是为True，就会无限循环下去，变成死循环，所以要特别留意while循环的退出条件。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Python之 break退出循环\n",
    "\n",
    "用 for 循环或者 while 循环时，如果要在循环体内直接退出循环，可以使用 break 语句。\n",
    "\n",
    "比如计算1至100的整数和，我们用while来实现："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "total = 0\n",
    "x = 1\n",
    "while True:\n",
    "    total = total + x\n",
    "    x = x + 1\n",
    "    if x > 100:\n",
    "        print('退出循环',x)\n",
    "        break\n",
    "print(total)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###  练习3：计算 1 + 2 + 4 + 8 + 16 + ... 的前20项的和"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "total = 0 # 记录总和\n",
    "x = 0 # 记录次数\n",
    "while True:\n",
    "    ???\n",
    "    x = x + ?\n",
    "    if x >19:\n",
    "        ???\n",
    "        ???\n",
    "print(total)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "以下程序是一个老师想统计学生的平均分，L里面记录了每个学生的分数，程序最终输出一个浮点数就是学生的平均分。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "L = [75, 98, 59, 81, 66, 43, 69, 85]\n",
    "total = 0  # 统计分数\n",
    "n = 0      # 统计人数\n",
    "for x in L:\n",
    "    n = n + 1\n",
    "    total = total + x\n",
    "print(total / n)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###  continue 调过部分循环\n",
    "\n",
    "* **在循环过程中**，如果 某一个条件满足后, 不希望 **执行循环代码，但是又不希望退出循环**，可以使用 `continue`\n",
    "* 也就是：在整个循环中，**只有某些条件**，不需要执行循环代码，而其他条件都需要执行\n",
    "\n",
    "现在老师只想统计及格分数的平均分，就要把 x < 60 的分数剔除掉，\n",
    "\n",
    "这时，利用 continue，可以做到当 x < 60的时候，\n",
    "\n",
    "不继续执行循环体的后续代码，直接进入下一次循环："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "L = [75, 98, 59, 81, 66, 43, 69, 85]\n",
    "total = 0\n",
    "n = 0\n",
    "for x in L:\n",
    "    if x < 60:\n",
    "        print('忽略的成绩', x)\n",
    "        continue\n",
    "    total = total + x\n",
    "    n = n + 1\n",
    "print(total / n)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 练习4：改写下面程序，计算0-100的奇数和\n",
    "\n",
    "### 补充知识：\n",
    "\n",
    "`%`是求余数, 例子： 5 % 3 = 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 改写下面程序，计算0-100的奇数和\n",
    "total = 0\n",
    "for i in range(0, 101):\n",
    "    if i % 2 == 0: # 是否为奇数 ‘%’是求余数\n",
    "        ???\n",
    "    ???\n",
    "    ???\n",
    "print(total)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Python之 多重循环"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for x in ['A', 'B', 'C']:\n",
    "    for y in ['1', '2', '3']:\n",
    "        print (x + y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 练习：\n",
    "\n",
    "#### 对100以内的两位数，请使用一个两重循环打印出所有十位数数字比个位数数字小的数，例如，23（2 < 3）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for x in [???]:\n",
    "    for y in [???]:\n",
    "        ???\n",
    "            ???\n",
    "    ???"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 练习2： 九九乘法表\n",
    "\n",
    "**需求** 输出 九九乘法表，格式如下：\n",
    "\n",
    "```\n",
    "1 * 1 = 1\t\n",
    "1 * 2 = 2\t2 * 2 = 4\t\n",
    "1 * 3 = 3\t2 * 3 = 6\t3 * 3 = 9\t\n",
    "1 * 4 = 4\t2 * 4 = 8\t3 * 4 = 12\t4 * 4 = 16\t\n",
    "1 * 5 = 5\t2 * 5 = 10\t3 * 5 = 15\t4 * 5 = 20\t5 * 5 = 25\t\n",
    "1 * 6 = 6\t2 * 6 = 12\t3 * 6 = 18\t4 * 6 = 24\t5 * 6 = 30\t6 * 6 = 36\t\n",
    "1 * 7 = 7\t2 * 7 = 14\t3 * 7 = 21\t4 * 7 = 28\t5 * 7 = 35\t6 * 7 = 42\t7 * 7 = 49\t\n",
    "1 * 8 = 8\t2 * 8 = 16\t3 * 8 = 24\t4 * 8 = 32\t5 * 8 = 40\t6 * 8 = 48\t7 * 8 = 56\t8 * 8 = 64\t\n",
    "1 * 9 = 9\t2 * 9 = 18\t3 * 9 = 27\t4 * 9 = 36\t5 * 9 = 45\t6 * 9 = 54\t7 * 9 = 63\t8 * 9 = 72\t9 * 9 = 81\n",
    "\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
